package JSF;

import Entidad.Seatshowtime;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import JSF.util.JsfUtil;
import JSF.util.PaginationHelper;
import SessionBean.SeatshowtimeFacade;

import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "seatshowtimeController")
@SessionScoped
public class SeatshowtimeController {

    private Seatshowtime current;
    private DataModel items = null;
    @EJB
    private SessionBean.SeatshowtimeFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private int idseatshowtime = 0;
    private String descripcionseatshowtime = "";
    private String Modo;

    public SeatshowtimeController() {
    }

    public int getIdseatshowtime() {
        return idseatshowtime;
    }

    public void setIdseatshowtime(int idseatshowtime) {
        this.idseatshowtime = idseatshowtime;
    }

    public String getDescripcionseatshowtime() {
        return descripcionseatshowtime;
    }

    public void setDescripcionseatshowtime(String descripcionseatshowtime) {
        this.descripcionseatshowtime = descripcionseatshowtime;
    }

    public String getModo() {
        return Modo;
    }

    public void setModo(String Modo) {
        this.Modo = Modo;
    }

    public int longCampo(String nomCampo) throws ClassNotFoundException {
        int lenCampo = 8;
        Class clase = Class.forName("Entidad.Seatshowtime");
        Field campo;
        try {
            campo = clase.getDeclaredField(nomCampo);
            Annotation[] anot = campo.getAnnotations();
            for (Annotation anot1 : anot) {
                int posLen = anot1.toString().indexOf("max");
                if (posLen > 0) {
                    String desanot = anot1.toString().substring(posLen);
                    int posIgual = desanot.indexOf("=");
                    String deslen = desanot.substring(posIgual);
                    int posComa = deslen.indexOf(",");
                    String loncampo = deslen.substring(1, posComa);
                    lenCampo = new Integer(loncampo);
                }
                int posSca = anot1.toString().indexOf("scale");
                if (posSca > 0) {
                    String desanot = anot1.toString().substring(posSca);
                    int posIgual = desanot.indexOf("=");
                    String deslen = desanot.substring(posIgual);
                    int posComa = deslen.indexOf(",");
                    String loncampo = deslen.substring(1, posComa);
                    if (new Integer(loncampo) != 0) {
                        lenCampo = new Integer(loncampo);
                    }
                }
            }
        } catch (NoSuchFieldException ex) {
            //Logger.getLogger(SubtemaController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            //Logger.getLogger(SubtemaController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return lenCampo;
    }

    public String campoNulo(String nomCampo) throws ClassNotFoundException {
        String noesNulo = "false";
        Class clase = Class.forName("Entidad.Seatshowtime");
        Field campo;
        try {
            campo = clase.getDeclaredField(nomCampo);
            Annotation[] anot = campo.getAnnotations();
            for (Annotation anot1 : anot) {
                int posLen = anot1.toString().indexOf("NotNull");
                if (posLen > 0) {
                    noesNulo = "true";
                }
            }
        } catch (NoSuchFieldException ex) {
            //Logger.getLogger(SubtemaController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            //Logger.getLogger(SubtemaController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return noesNulo;
    }

    public Seatshowtime getSelected() {
        if (current == null) {
            current = new Seatshowtime();
            selectedItemIndex = -1;
        }
        return current;
    }

    private SeatshowtimeFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    int itemscount = 0;
                    //if (idseatshowtime == 0 && descripcionseatshowtime.equals("")) {
                    itemscount = getFacade().count();
                    //} else if (idseatshowtime != 0) {
                    //    itemscount = getFacade().countByIdSeatshowtime(idseatshowtime);
                    //} else if (!descripcionseatshowtime.equals("")) {
                    //    itemscount = getFacade().countByDescripcionSeatshowtime(descripcionseatshowtime);
                    //}
                    return itemscount;
                }

                @Override
                public DataModel createPageDataModel() {
                    ListDataModel seatshowtimeListDM = null;
                    //if (idseatshowtime == 0 && descripcionseatshowtime.equals("")) {
                    seatshowtimeListDM = new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                    //} else if (idseatshowtime != 0) {
                    //    seatshowtimeListDM = new ListDataModel(getFacade().findByIdSeatshowtimeRange(idseatshowtime, new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                    //} else if (!descripcionseatshowtime.equals("")) {
                    //    seatshowtimeListDM = new ListDataModel(getFacade().findByDescripcionSeatshowtimeRange(descripcionseatshowtime, new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                    //}
                    return seatshowtimeListDM;
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "/paginas/seatshowtime/List";
    }

    public String prepareView() {
        current = (Seatshowtime) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        Modo = "View";
        return "Edit";
    }

    public String prepareCreate() {
        current = new Seatshowtime();
        selectedItemIndex = -1;
        Modo = "Create";
        return "Edit";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("resources/Bundle").getString("SeatshowtimeCreated"));
            return prepareList();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Seatshowtime) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        Modo = "Edit";
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("resources/Bundle").getString("SeatshowtimeUpdated"));
            return "List";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String confirma() {
        if ("Create".equals(Modo)) {
            return create();
        } else {
            return update();
        }
    }

    public String destroy() {
        current = (Seatshowtime) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("resources/Bundle").getString("SeatshowtimeDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("resources/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    public void recreateModel() {
        items = null;
    }

    public void recreateModelPage() {
        getPagination().setPage(0);
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Seatshowtime.class)
    public static class SeatshowtimeControllerConverter implements Converter {

        private static final String SEPARATOR = "#";
        private static final String SEPARATOR_ESCAPED = "\\#";

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            SeatshowtimeController controller = (SeatshowtimeController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "seatshowtimeController");
            return controller.ejbFacade.find(getKey(value));
        }

        Entidad.SeatshowtimePK getKey(String value) {
            Entidad.SeatshowtimePK key;
            String values[] = value.split(SEPARATOR_ESCAPED);
            key = new Entidad.SeatshowtimePK();
            key.setShowtimeID(Integer.parseInt(values[0]));
            key.setCinemaID(Integer.parseInt(values[1]));
            key.setSeatID(Integer.parseInt(values[2]));
            return key;
        }

        String getStringKey(Entidad.SeatshowtimePK value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value.getShowtimeID());
            sb.append(SEPARATOR);
            sb.append(value.getCinemaID());
            sb.append(SEPARATOR);
            sb.append(value.getSeatID());
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Seatshowtime) {
                Seatshowtime o = (Seatshowtime) object;
                return getStringKey(o.getSeatshowtimePK());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + SeatshowtimeController.class.getName());
            }
        }
    }
}
